﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ErrorModule.cs" company="Anton Frattaroli">
//   Copyright (c) Anton Frattaroli. All rights reserved.
// </copyright>
// <summary>
//   Defines the ErrorModule implementation class of the IHttpModule interface to handle error events.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Lidocaine
{
    using System;
    using System.Web;
    
    /// <summary>
    /// The ErrorModule class implements the IHttpModule interface to handle error events.
    /// </summary>
    public class ErrorModule : IHttpModule
    {
        /// <summary>
        /// Adds event handlers to the application lifecycle.
        /// </summary>
        /// <param name="context">The HttpApplication object for the request.</param>
        public virtual void Init(HttpApplication context)
        {
            context.Error += new EventHandler(this.ErrorHandler);
        }

        /// <summary>
        /// Implements the standard Dispose() method of the IHttpModule interface.
        /// </summary>
        public virtual void Dispose()
        {
        }

        /// <summary>
        /// Routes users to error page on error event.
        /// </summary>
        /// <param name="sender">The HttpApplication object for the request.</param>
        /// <param name="e">The EventArgs object for the request.</param>
        private void ErrorHandler(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            if (app.Request.Path != Environmental.ErrorUrl.PathAndQuery)
            {
                app.Response.Redirect("~" + Environmental.ErrorUrl);
            }
        }
    }
}